<?php
/**
 * Created by PhpStorm.
 * User: yuanluke
 * Date: 3/14/17
 * Time: 23:53
 */

namespace App\Http\Utils\ControllerTrait;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Log;
use App\Http\Utils\Common\OperResult;
use Imagick;

trait WebUploadNewTrait {

    /**
     * 上传图片
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function webUploadImg(Request $req) {
        try {
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            if ($req->hasFile('file') && $req->file('file')->isValid()) {
                $fileData = $req->file('file');
                $fExtName = strtolower($fileData->getClientOriginalExtension());
                $fSize = $fileData->getClientSize();

                if ($fExtName!='png' && $fExtName!='jpg' && $fExtName!='jpeg' && $fExtName!='gif') {
                    return response()->json(['error'=>1, 'message'=>OperResult::CODE_UPLOAD_IMG_EXT_FAIL_DESC]);
                }
                if ($fSize>OperResult::UPLOAD_IMG_MAX_SIZE*1024) {
                    return response()->json(['error'=>1, 'message'=>OperResult::CODE_UPLOAD_IMG_SIZE_FAIL_DESC]);
                }

                $fNamePrefix = uniqid(true);
                $fName = $fNamePrefix.'.'.$fExtName;
                $fNameThumb = 'thumb_'.$fNamePrefix.'.'.$fExtName;
                $saveDir = base_path().'/public/assets/up/'.$req->input('destpos').'/';
                if (!file_exists($saveDir)) {
                    mkdir($saveDir, 0777, true);
                }

                //处理图片
//                $imagick = new Imagick($fileData->getRealPath());
//                $picWH = $imagick->getImageGeometry();
//                $imagick->thumbnailImage($picWH['width']/2, $picWH['height']/2, true);
//                $imagick->writeImage($saveDir.$fNameThumb);
//                $imagick->destroy();
//                Log::debug(sprintf('img w=%d   h=%d', $picWH['width'], $picWH['height']));


                $fileData->move($saveDir, $fName);
                return response()->json(["jsonrpc" => "2.0", "result"=>'/assets/up/'.$req->input('destpos').'/'.$fName, "id"=>"id"]);
//                return response()->json(['error'=>0, 'url'=>'/assets/up/'.$req->input('destpos').'/'.$fName, 'fname'=>$fName]);
            } else {
                return response()->json(["jsonrpc"=>"2.0", "error" =>["code"=>-1, "message"=>"文件名入参不存在"], "id"=>"id"]);
//                return response()->json(['error'=>-1]);
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
        } catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
        }
    }

}